﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace exMath.Sequences
{
    public class FibonacciSequence : INumberSequence
    {
        private double[] _fibCache;
        private double _currentvalue;
        private double _currentN;

        public double Current
        {
            get
            {
                return _currentvalue;
            }
        }

        public FibonacciSequence()
        {
            _fibCache = new double[2];
            _currentN = 0.0;
            _currentvalue = 0.0;
        }

        private double fibonacciHelper(double n)
        {
            if (n == 0.0)                           
                return 0.0;
            if (n == 1.0)
                return 1.0;
            else
                return fibonacciHelper(n - 1.0) + fibonacciHelper(n - 2.0);
        }

        public void Next()
        {
            if (_currentN == 0.0)
            {
                _currentvalue = 0.0;
                _fibCache[0] = 0.0;
            }
            if (_currentN == 1.0)
            {
                _currentvalue = 1.0;
                _fibCache[1] = 1.0;
            }
            else
            {
                _currentvalue = _fibCache[0] + _fibCache[1];
                _fibCache[0] = _fibCache[1];
                _fibCache[1] = _currentvalue;
            }

            _currentN += 1.0;
        }

        public void Reset()
        {
            _currentN = 0.0;
            _currentvalue = 0.0;
            _fibCache[0] = 0.0;
            _fibCache[1] = 0.0;
        }

        public double CalculateItemN(double n)
        {
            return fibonacciHelper(n);
        }
    }
}
